// 活动详情页面
const { 
  getActivityDetail, 
  registerActivity, 
  cancelRegistration,
  checkRegistrationStatus,
  getActivityComments,
  publishComment
} = require('../../../api/activities')
const { processActivityData, formatDateTime, formatActivityTime } = require('../../../utils/dataFormatter')
const { getCurrentUser } = require('../../../utils/auth')

Page({
  data: {
    activityId: '',
    activity: null,
    loading: true,
    // 评论相关数据
    comments: [],
    commentText: '',
    isInputFocused: false,
    // 页面状态
    isSubmitting: false,
    hasError: false,
    errorMessage: '',
    // 报名状态
    isRegistered: false,
    participationId: null,
    // 当前用户头像
    currentUserAvatar: '',
    // 当前用户身份标识
    currentUserIdentity: ''
  },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '活动信息加载中...',

  // 显示全局加载
  showGlobalLoading(text = '活动信息加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('活动信息加载中...')
    const { id } = options
    if (id) {
      this.setData({ 
        activityId: id,
        hasError: false,
        errorMessage: ''
      })
      this.loadActivity(id)
    } else {
      this.setData({
        hasError: true,
        errorMessage: '活动ID不存在',
        loading: false
      })
      
      // 隐藏全局加载状态
      this.hideGlobalLoading()
      
      wx.showToast({ title: '活动ID不存在', icon: 'none' })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载活动详情
  async loadActivity(id) {
    this.setData({ 
      loading: true,
      hasError: false,
      errorMessage: ''
    })
    
    try {
      // 调用API获取活动详情
      const result = await getActivityDetail(id)
      
      if (result.success) {
        const activityData = result.data
        
        // 使用工具函数处理活动数据
        const processedActivity = processActivityData(activityData, {
          stripHtml: false, // 详情页面保留HTML格式
          formatTime: true
        })
        
        // 获取参与人数和最大参与人数
        const participants = activityData.current_participants || activityData.participant_count || 0
        const maxParticipants = activityData.max_participants || 0
        
        // 构建活动对象
        const activity = {
          id: activityData.id,
          title: activityData.title,
          subtitle: activityData.subtitle,
          content: activityData.content,
          startTime: processedActivity.startTime,
          endTime: processedActivity.endTime,
          status: activityData.status,
          statusText: this.getStatusText(activityData.status),
          participants: participants,
          maxParticipants: maxParticipants,
          participationRate: this.calculateParticipationRate(participants, maxParticipants),
          contact: activityData.contact_person,
          phone: activityData.contact_phone,
          images: activityData.images ? activityData.images.map(img => {
            // 确保图片URL是完整的，如果不是完整URL则添加基础路径
            let imageUrl = img.image_url;
            
            if (imageUrl) {
              // 如果URL包含临时路径，尝试转换为正确的服务器路径
              if (imageUrl.includes('/_tmp_/')) {
                // 将临时路径转换为uploads路径
                const fileName = imageUrl.split('/').pop();
                imageUrl = `http://localhost:3000/uploads/${fileName}`;
              } else if (imageUrl.includes('/uploads/')) {
                // 如果已经是uploads路径，确保有完整的服务器URL
                if (!imageUrl.startsWith('http')) {
                  imageUrl = `http://localhost:3000${imageUrl}`;
                }
              } else if (!imageUrl.startsWith('http')) {
                // 如果是相对路径，添加服务器基础URL
                imageUrl = `http://localhost:3000${imageUrl.startsWith('/') ? '' : '/'}${imageUrl}`;
              }
            }
            return imageUrl;
          }).filter(url => url && url.trim() !== '') : [],
          createTime: formatDateTime(activityData.created_at),
          updateTime: formatDateTime(activityData.updated_at),
          tags: activityData.tags || []
        }
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: activity.title
        })
        
        this.setData({
          activity: activity,
          loading: false,
          hasError: false
        })
        
        // 隐藏全局加载状态
        this.hideGlobalLoading()
        
        // 加载评论数据
        this.loadComments(id)
        
        // 检查用户报名状态
        this.checkUserRegistrationStatus(id)
        
        // 获取当前用户头像
        this.loadCurrentUserAvatar()
        
        // 获取当前用户身份标识
        this.loadCurrentUserIdentity()
      } else {
        throw new Error(result.message || '获取活动详情失败')
      }
    } catch (error) {
      this.setData({ 
        loading: false,
        hasError: true,
        errorMessage: error.message || '加载失败，请重试'
      })
      
      // 隐藏全局加载状态
      this.hideGlobalLoading()
      
      wx.showToast({
        title: error.message || '加载失败，请重试',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载评论数据
  async loadComments(activityId) {
    try {
      
      // 调用真实的评论API
      const result = await getActivityComments(activityId, {
        page: 1,
        limit: 20
      })
      
      if (result.success && result.data.comments) {
        // 处理评论数据，确保每个评论都有完整的数据结构
        const processedComments = result.data.comments.map(comment => {
          const processedAvatar = this.processAvatarUrl(comment.user_avatar)
          return {
            id: comment.id || '',
            userName: comment.user_name || '匿名用户',
            userAvatar: processedAvatar, // 处理头像URL
            userIdentity: this.getUserIdentity(comment.user_role), // 添加用户身份标识
            content: comment.content || '',
            createTime: this.formatTime(new Date(comment.created_at)),
            likeCount: comment.like_count || 0,
            isLiked: false, // 这里可以根据用户点赞状态设置
            isExpanded: false,
            // 回复相关字段
            showReplyInput: false,
            replyText: '',
            replies: (comment.replies || []).map(reply => {
              const replyAvatar = this.processAvatarUrl(reply.user_avatar)
              return {
                id: reply.id || '',
                userName: reply.user_name || '匿名用户',
                userAvatar: replyAvatar, // 处理回复的头像URL
                userIdentity: this.getUserIdentity(reply.user_role), // 添加回复的用户身份标识
                content: reply.content || '',
                createTime: this.formatTime(new Date(reply.created_at)),
                likeCount: reply.like_count || 0,
                isLiked: false
              }
            })
          }
        })
        
        this.setData({
          comments: processedComments
        })
        
      } else {
        this.setData({
          comments: []
        })
      }
    } catch (error) {
      // 即使评论加载失败，也不影响页面显示
      this.setData({
        comments: []
      })
    }
  },

  // 获取当前用户头像
  loadCurrentUserAvatar() {
    try {
      const currentUser = getCurrentUser()
      if (currentUser && currentUser.avatar) {
        this.setData({
          currentUserAvatar: currentUser.avatar
        })
      } else {
      }
    } catch (error) {
    }
  },

  // 获取用户身份标识
  getUserIdentity(role) {
    const identityMap = {
      'admin': '管理员',
      'citizen': '村民',
      'village_leader': '村领导',
      'party_member': '党员',
      'volunteer': '志愿者'
    }
    return identityMap[role] || '村民'
  },

  // 获取当前用户身份标识
  loadCurrentUserIdentity() {
    try {
      const currentUser = getCurrentUser()
      if (currentUser && currentUser.role) {
        const identity = this.getUserIdentity(currentUser.role)
        this.setData({
          currentUserIdentity: identity
        })
      } else {
        this.setData({
          currentUserIdentity: '村民'
        })
      }
    } catch (error) {
      this.setData({
        currentUserIdentity: '村民'
      })
    }
  },

  // 检查用户报名状态
  async checkUserRegistrationStatus(activityId) {
    try {
      const currentUser = getCurrentUser()
      if (!currentUser) {
        return
      }


      
      const result = await checkRegistrationStatus(activityId, currentUser.userId)
      
      if (result.success) {
        const { isRegistered, participationId, registrationTime, status } = result.data
        
        this.setData({
          isRegistered: isRegistered,
          participationId: participationId
        })
        
        console.log('用户报名状态:', {
          isRegistered,
          participationId,
          registrationTime,
          status
        })
      } else {
      }
    } catch (error) {
      // 检查报名状态失败不影响页面正常显示
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'upcoming': '即将开始',
      'active': '进行中',
      'completed': '已结束',
      'cancelled': '已取消'
    }
    return statusMap[status] || '未知状态'
  },

  // 计算参与率
  calculateParticipationRate(participants, maxParticipants) {
    if (!maxParticipants || maxParticipants <= 0) {
      return 0
    }
    const rate = (participants / maxParticipants) * 100
    return Math.round(rate)
  },

  // 处理头像URL
  processAvatarUrl(avatarUrl) {
    
    if (!avatarUrl || avatarUrl.trim() === '') {
      return ''
    }
    
    // 如果已经是完整的URL，直接返回
    if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
      return avatarUrl
    }
    
    // 如果是相对路径，添加服务器基础URL
    if (avatarUrl.startsWith('/')) {
      const fullUrl = `http://localhost:3000${avatarUrl}`
      return fullUrl
    }
    
    // 如果是文件名，添加uploads路径
    const fullUrl = `http://localhost:3000/uploads/${avatarUrl}`
    return fullUrl
  },

  // 获取默认头像
  getDefaultAvatar(userName) {
    if (!userName || userName.trim() === '') {
      return ''
    }
    
    // 返回用户名首字母作为默认头像
    return userName.charAt(0).toUpperCase()
  },

  // 参与活动
  onJoinActivity() {
    const { activity, isRegistered } = this.data
    if (!activity) return

    if (activity.status === 'completed' || activity.status === 'cancelled') {
      wx.showToast({ title: '活动已结束', icon: 'none' })
      return
    }

    // 如果已经报名，显示取消报名确认
    if (isRegistered) {
      wx.showModal({
        title: '取消报名',
        content: `确定要取消报名"${activity.title}"活动吗？`,
        confirmText: '确认取消',
        cancelText: '继续参与',
        success: (res) => {
          if (res.confirm) {
            this.cancelParticipation()
          }
        }
      })
      return
    }

    // 检查报名人数是否已满
    if (activity.participants >= activity.maxParticipants) {
      wx.showModal({
        title: '报名已满',
        content: '该活动报名人数已满，请关注其他活动。',
        showCancel: false,
        confirmText: '知道了'
      })
      return
    }

    // 根据活动状态显示不同的确认信息
    let confirmTitle = '确认报名'
    let confirmContent = `确定要报名参加"${activity.title}"活动吗？`
    
    if (activity.status === 'upcoming') {
      confirmContent = `活动将于 ${activity.startTime} 开始，确定要报名参加"${activity.title}"活动吗？`
    }

    wx.showModal({
      title: confirmTitle,
      content: confirmContent,
      confirmText: '确认报名',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.submitParticipation()
        }
      }
    })
  },

  // 提交参与申请
  async submitParticipation() {
    if (this.data.isSubmitting) return
    
    // 检查是否已经报名
    if (this.data.isRegistered) {
      wx.showToast({
        title: '您已经报名过该活动',
        icon: 'none'
      })
      return
    }
    
    // 检查用户是否已登录
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showModal({
        title: '请先登录',
        content: '您需要先登录才能报名参加活动',
        showCancel: false,
        confirmText: '去登录',
        success: () => {
          wx.navigateTo({
            url: '/pages/auth/login/index'
          })
        }
      })
      return
    }
    
    this.setData({ isSubmitting: true })
    try {
      const { activityId } = this.data
      
      // 调用报名API
      const result = await registerActivity(activityId, {
        userId: currentUser.userId,
        notes: '用户报名参加活动'
      })
      
      if (result.success) {
        wx.showToast({ 
          title: '报名成功！', 
          icon: 'success',
          duration: 2000
        })
        
        // 更新参与人数和报名状态
        const { activity } = this.data
        const newParticipants = activity.participants + 1
        this.setData({
          'activity.participants': newParticipants,
          'activity.participationRate': this.calculateParticipationRate(newParticipants, activity.maxParticipants),
          isRegistered: true,
          participationId: result.data.participationId,
          isSubmitting: false
        })
      } else {
        throw new Error(result.message || '报名失败')
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '报名失败，请重试',
        icon: 'none'
      })
      this.setData({ isSubmitting: false })
    }
  },

  // 取消报名
  async cancelParticipation() {
    if (this.data.isSubmitting) return
    
    // 检查用户是否已登录
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showModal({
        title: '请先登录',
        content: '您需要先登录才能取消报名',
        showCancel: false,
        confirmText: '去登录',
        success: () => {
          wx.navigateTo({
            url: '/pages/auth/login/index'
          })
        }
      })
      return
    }
    
    this.setData({ isSubmitting: true })
    try {
      const { activityId } = this.data
      
      // 调用取消报名API
      const result = await cancelRegistration(activityId, {
        userId: currentUser.userId
      })
      
      if (result.success) {
        wx.showToast({ 
          title: '取消报名成功！', 
          icon: 'success',
          duration: 2000
        })
        
        // 更新参与人数和报名状态
        const { activity } = this.data
        const newParticipants = Math.max(0, activity.participants - 1)
        this.setData({
          'activity.participants': newParticipants,
          'activity.participationRate': this.calculateParticipationRate(newParticipants, activity.maxParticipants),
          isRegistered: false,
          participationId: null,
          isSubmitting: false
        })
      } else {
        throw new Error(result.message || '取消报名失败')
      }
    } catch (error) {
      // 详细的错误信息处理
      let errorMessage = '取消报名失败，请重试'
      
      if (error.message) {
        errorMessage = error.message
      } else if (error.status) {
        switch (error.status) {
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = '没有权限取消报名'
            break
          case 404:
            errorMessage = '活动不存在'
            break
          case 400:
            errorMessage = '无法取消报名，请检查报名状态'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
          default:
            errorMessage = '网络错误，请检查网络连接'
        }
      } else if (error.type === 'network') {
        errorMessage = '网络连接失败，请检查网络设置'
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
      
      this.setData({ isSubmitting: false })
    }
  },

  // 联系负责人
  onContact() {
    const { activity } = this.data
    if (!activity) return

    // 检查是否为开发环境
    const isDev = wx.getSystemInfoSync().platform === 'devtools'
    
    if (isDev) {
      // 开发环境中显示提示
      wx.showModal({
        title: '拨打电话',
        content: `确定要拨打 ${activity.phone} 吗？`,
        confirmText: '拨打',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: activity.phone,
              fail: () => {
                wx.showToast({ title: '拨号失败', icon: 'none' })
              }
            })
          }
        }
      })
    } else {
      // 生产环境直接拨打电话
      wx.makePhoneCall({
        phoneNumber: activity.phone,
        fail: () => {
          wx.showToast({ title: '拨号失败', icon: 'none' })
        }
      })
    }
  },

  // 分享活动
  onShare() {
    const { activity } = this.data
    if (!activity) return

    return {
      title: activity.title,
      desc: activity.description,
      path: `/pages/activity/detail/index?id=${activity.id}`
    }
  },

  // 评论输入
  onCommentInput(e) {
    const value = e.detail.value
    this.setData({ 
      commentText: value
    })
  },

  // 输入框获得焦点
  onCommentInputFocus() {
    this.setData({ isInputFocused: true })
  },

  // 输入框失去焦点
  onCommentInputBlur() {
    setTimeout(() => {
      this.setData({ isInputFocused: false })
    }, 200)
  },

  // 提交评论
  async onSubmitComment() {
    const { commentText, isSubmitting, activityId } = this.data
    
    if (isSubmitting) return
    
    // 数据校验
    if (!commentText || commentText.trim() === '') {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    if (commentText.trim().length > 200) {
      wx.showToast({
        title: '评论内容不能超过200个字符',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 检查用户是否已登录
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showModal({
        title: '请先登录',
        content: '您需要先登录才能发表评论',
        showCancel: false,
        confirmText: '去登录',
        success: () => {
          wx.navigateTo({
            url: '/pages/auth/login/index'
          })
        }
      })
      return
    }
    
    this.setData({ 
      isSubmitting: true
    })
    try {
      // 调用真实的评论发布API
      
      // 确保activityId是数字类型
      const activityIdNum = parseInt(activityId)
      if (isNaN(activityIdNum)) {
        throw new Error('活动ID格式不正确')
      }
      
      const result = await publishComment(activityIdNum, {
        userId: currentUser.userId,
        content: commentText.trim()
      })
      
      
      if (result.success) {
        // 创建新评论对象
        const newComment = {
          id: result.data.comment.id,
          userName: result.data.comment.user_name || currentUser.name || '我',
          userAvatar: this.processAvatarUrl(result.data.comment.user_avatar || currentUser.avatar || ''), // 处理头像URL，确保有默认值
          userIdentity: this.getUserIdentity(result.data.comment.user_role || currentUser.role), // 添加用户身份标识
          content: result.data.comment.content,
          createTime: this.formatTime(new Date(result.data.comment.created_at)),
          likeCount: result.data.comment.like_count || 0,
          isLiked: false,
          isExpanded: false,
          showReplyInput: false,
          replyText: '',
          replies: []
        }
        
        
        // 添加到评论列表开头（最新评论显示在前面）
        const comments = [newComment, ...this.data.comments]
        
        this.setData({
          comments: comments,
          commentText: '',
          isSubmitting: false
        })
        
        wx.showToast({ 
          title: '评论发布成功！', 
          icon: 'success',
          duration: 1500
        })
        
      } else {
        throw new Error(result.message || '评论发布失败')
      }
    } catch (error) {
      // 详细的错误信息处理
      let errorMessage = '评论发布失败，请重试'
      
      if (error.message) {
        errorMessage = error.message
      } else if (error.status) {
        switch (error.status) {
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = '没有权限发表评论'
            break
          case 404:
            errorMessage = '活动不存在'
            break
          case 400:
            errorMessage = '评论内容不符合要求'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
          default:
            errorMessage = '网络错误，请检查网络连接'
        }
      } else if (error.type === 'network') {
        errorMessage = '网络连接失败，请检查网络设置'
      }
      
      // 显示错误信息
      this.setData({
        isSubmitting: false
      })
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  },

  // 点赞评论
  async onLikeComment(e) {
    const { id } = e.currentTarget.dataset
    const { comments, isSubmitting } = this.data
    
    if (isSubmitting) return
    
    // 检查用户是否已登录
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showModal({
        title: '请先登录',
        content: '您需要先登录才能点赞评论',
        showCancel: false,
        confirmText: '去登录',
        success: () => {
          wx.navigateTo({
            url: '/pages/auth/login/index'
          })
        }
      })
      return
    }
    
    // 防止重复点赞
    const comment = comments.find(c => c.id === id)
    if (comment && comment.isLiked) {
      wx.showToast({ title: '已经点赞过了', icon: 'none' })
      return
    }
    
    this.setData({ isSubmitting: true })
    try {
      // 调用真实的点赞API
      const result = await likeComment(parseInt(id), {
        userId: currentUser.userId
      })
      
      if (result.success) {
        // 更新评论点赞状态
        const updatedComments = comments.map(comment => {
          if (comment.id === id) {
            return { 
              ...comment, 
              likeCount: (comment.likeCount || 0) + 1,
              isLiked: true
            }
          }
          return comment
        })
        
        this.setData({ 
          comments: updatedComments,
          isSubmitting: false
        })
        
        wx.showToast({ 
          title: '点赞成功！', 
          icon: 'success',
          duration: 1000
        })
      } else {
        throw new Error(result.message || '点赞失败')
      }
    } catch (error) {
      console.error('点赞评论失败:', error)
      let errorMessage = '点赞失败，请重试'
      if (error.message) {
        errorMessage = error.message
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
      
      this.setData({ isSubmitting: false })
    }
  },

  // 展开/收起评论
  onToggleComment(e) {
    const { id } = e.currentTarget.dataset
    const { comments } = this.data
    
    // 找到对应的评论并切换展开状态
    const updatedComments = comments.map(comment => {
      if (comment.id === id) {
        return {
          ...comment,
          isExpanded: !comment.isExpanded
        }
      }
      return comment
    })
    
    this.setData({
      comments: updatedComments
    })
  },

  // 显示回复输入框
  onShowReplyInput(e) {
    const { id } = e.currentTarget.dataset
    const { comments } = this.data
    
    // 先关闭所有其他评论的回复输入框
    const updatedComments = comments.map(comment => {
      if (comment.id === id) {
        return {
          ...comment,
          showReplyInput: !comment.showReplyInput,
          replyText: ''
        }
      } else {
        return {
          ...comment,
          showReplyInput: false,
          replyText: ''
        }
      }
    })
    
    this.setData({
      comments: updatedComments
    })
  },

  // 回复输入
  onReplyInput(e) {
    const { id } = e.currentTarget.dataset
    const value = e.detail.value
    const { comments } = this.data
    
    const updatedComments = comments.map(comment => {
      if (comment.id === id) {
        return {
          ...comment,
          replyText: value
        }
      }
      return comment
    })
    
    this.setData({
      comments: updatedComments
    })
  },

  // 提交回复
  async onSubmitReply(e) {
    const { id } = e.currentTarget.dataset
    const { comments, activityId, isSubmitting } = this.data
    
    if (isSubmitting) return
    
    const comment = comments.find(c => c.id === id)
    if (!comment || !comment.replyText || comment.replyText.trim() === '') {
      wx.showToast({ title: '请输入回复内容', icon: 'none' })
      return
    }
    
    // 检查用户是否已登录
    const currentUser = getCurrentUser()
    if (!currentUser) {
      wx.showModal({
        title: '请先登录',
        content: '您需要先登录才能回复评论',
        showCancel: false,
        confirmText: '去登录',
        success: () => {
          wx.navigateTo({
            url: '/pages/auth/login/index'
          })
        }
      })
      return
    }
    
    this.setData({ isSubmitting: true })
    try {
      // 调用真实的回复API
      console.log('准备调用回复API，活动ID:', activityId, '父评论ID:', id, '用户ID:', currentUser.userId, '回复内容:', comment.replyText.trim())
      
      // 确保activityId是数字类型
      const activityIdNum = parseInt(activityId)
      if (isNaN(activityIdNum)) {
        throw new Error('活动ID格式不正确')
      }
      
      const result = await publishComment(activityIdNum, {
        userId: currentUser.userId,
        content: comment.replyText.trim(),
        parentId: parseInt(id) // 父评论ID
      })
      
      console.log('回复API调用结果:', result)
      
      if (result.success) {
        // 创建新回复对象
        const newReply = {
          id: result.data.comment.id,
          userName: result.data.comment.user_name || currentUser.name || '我',
          userAvatar: this.processAvatarUrl(result.data.comment.user_avatar || currentUser.avatar || ''), // 处理头像URL，确保有默认值
          userIdentity: this.getUserIdentity(result.data.comment.user_role || currentUser.role), // 添加用户身份标识
          content: result.data.comment.content,
          createTime: this.formatTime(new Date(result.data.comment.created_at)),
          likeCount: result.data.comment.like_count || 0,
          isLiked: false
        }
        
        console.log('新回复对象:', newReply)
        console.log('处理后的回复头像URL:', newReply.userAvatar)
        
        // 更新评论列表，添加回复
        const updatedComments = comments.map(c => {
          if (c.id === id) {
            return {
              ...c,
              replies: [...(c.replies || []), newReply],
              showReplyInput: false,
              replyText: ''
            }
          }
          return c
        })
        
        this.setData({
          comments: updatedComments,
          isSubmitting: false
        })
        
        wx.showToast({ 
          title: '回复成功！', 
          icon: 'success',
          duration: 1500
        })
        
        console.log('回复发布成功，新回复:', newReply)
      } else {
        throw new Error(result.message || '回复发布失败')
      }
    } catch (error) {
      console.error('提交回复失败:', error)
      // 详细的错误信息处理
      let errorMessage = '回复发布失败，请重试'
      
      if (error.message) {
        errorMessage = error.message
      } else if (error.status) {
        switch (error.status) {
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = '没有权限回复评论'
            break
          case 404:
            errorMessage = '评论不存在'
            break
          case 400:
            errorMessage = '回复内容不符合要求'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
          default:
            errorMessage = '网络错误，请检查网络连接'
        }
      } else if (error.type === 'network') {
        errorMessage = '网络连接失败，请检查网络设置'
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
      
      this.setData({ isSubmitting: false })
    }
  },

  // 取消回复
  onCancelReply(e) {
    const { id } = e.currentTarget.dataset
    const { comments } = this.data
    
    const updatedComments = comments.map(comment => {
      if (comment.id === id) {
        return {
          ...comment,
          showReplyInput: false,
          replyText: ''
        }
      }
      return comment
    })
    
    this.setData({
      comments: updatedComments
    })
  },

  // 格式化时间
  formatTime(date) {
    if (!date) return ''
    
    try {
      const dateObj = new Date(date)
      if (isNaN(dateObj.getTime())) return ''
      
      const year = dateObj.getFullYear()
      const month = String(dateObj.getMonth() + 1).padStart(2, '0')
      const day = String(dateObj.getDate()).padStart(2, '0')
      const hour = String(dateObj.getHours()).padStart(2, '0')
      const minute = String(dateObj.getMinutes()).padStart(2, '0')
      
      return `${year}年${month}月${day}日 ${hour}:${minute}`
    } catch (error) {
      console.error('时间格式化错误:', error)
      return ''
    }
  },

  // 图片加载错误处理
  onImageError(e) {
    const { index } = e.currentTarget.dataset
    console.log('图片加载失败，索引:', index)
    
    // 可以在这里设置默认图片或隐藏图片
    const { activity } = this.data
    if (activity && activity.images && activity.images[index]) {
      // 可以设置一个默认图片URL
      const updatedImages = [...activity.images]
      updatedImages[index] = '/assets/default-image.png' // 默认图片路径
      
      this.setData({
        'activity.images': updatedImages
      })
    }
  },

  // 头像加载错误处理
  onAvatarError(e) {
    const { id } = e.currentTarget.dataset
    console.log('头像加载失败，评论ID:', id)
    
    // 找到对应的评论并清空头像URL，这样会显示文字头像
    const { comments } = this.data
    const updatedComments = comments.map(comment => {
      if (comment.id === id) {
        return {
          ...comment,
          userAvatar: ''
        }
      }
      
      // 检查回复中的头像
      if (comment.replies && comment.replies.length > 0) {
        const updatedReplies = comment.replies.map(reply => {
          if (reply.id === id) {
            return {
              ...reply,
              userAvatar: ''
            }
          }
          return reply
        })
        
        return {
          ...comment,
          replies: updatedReplies
        }
      }
      
      return comment
    })
    
    this.setData({
      comments: updatedComments
    })
    
    // 显示提示信息
    wx.showToast({
      title: '头像加载失败',
      icon: 'none',
      duration: 1000
    })
  },

  // 预览图片
  onPreviewImage(e) {
    const { current, urls } = e.currentTarget.dataset
    const { activity } = this.data
    
    if (!activity || !activity.images || activity.images.length === 0) {
      wx.showToast({ title: '暂无图片', icon: 'none' })
      return
    }
    
    wx.previewImage({
      current: current || activity.images[0],
      urls: urls || activity.images
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    const { activityId } = this.data
    if (activityId) {
      this.loadActivity(activityId).finally(() => {
        wx.stopPullDownRefresh()
      })
    } else {
      wx.stopPullDownRefresh()
    }
  },

  // 页面分享
  onShareAppMessage() {
    const { activity } = this.data
    if (!activity) return {}
    
    return {
      title: activity.title,
      desc: activity.subtitle || '快来参与这个精彩活动吧！',
      path: `/pages/activity/detail/index?id=${activity.id}`,
      imageUrl: activity.images && activity.images.length > 0 ? activity.images[0] : ''
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    const { activity } = this.data
    if (!activity) return {}
    
    return {
      title: activity.title,
      query: `id=${activity.id}`,
      imageUrl: activity.images && activity.images.length > 0 ? activity.images[0] : ''
    }
  },

  // 页面显示时刷新数据
  onShow() {
    // 如果页面已经加载过，可以在这里添加刷新逻辑
    const { activityId, loading } = this.data
    if (activityId && !loading) {
      // 可以添加一些轻量级的刷新逻辑
      console.log('页面显示，活动ID:', activityId)
    }
  },

  // 页面隐藏时保存状态
  onHide() {
    // 可以在这里保存一些页面状态
    console.log('页面隐藏')
  },

  // 页面卸载时清理
  onUnload() {
    // 清理定时器等资源
    console.log('页面卸载')
  }
})
